package com.jinher.lib
{
	import __AS3__.vec.Vector;
	
	import com.adobe.serialization.json.*;
	import com.jinher.lib.Const.AppConst;
	import com.jinher.lib.Const.LnConst;
	import com.jinher.lib.Module.*;
	import com.jinher.lib.encrypt.Encryption;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;

	/**
	 * 创建人：王曙光
	 * 创建时间：
	 * 功能描述：系统业务逻辑
	 */	
	public class App
	{
		//Event 数据获取成功
		public static var Event_App_Complate:String="com.jinher.Event_App_Complate";
		//Event 数据获取失败
		public static var Event_App_Error:String="com.jinher.Event_App_Error";
		//用于传递数据
		public var data:Object=null;
		//事件调度
		private var _eventDispatcher:EventDispatcher=null;
		private var cnet:Net=null;		
		private var config:Config=null;

		/**********************************************************
		 * private function start
		 */

		//递归获取某个用户所在部门的串1,1001,1011
		private function getFDept(deptid:String, deptlist:Array):void
		{
			var sqlHelper:SqlHelper=new SqlHelper();
			var paramsArray:Array=new Array();
			paramsArray.push({key: "deptid", value: deptid});
			var sql:String="select * from dept where deptid = @deptid";
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, paramsArray);
			var _tempdeptid:String=String(sqlData.DataTable[0].DeptID);
			deptlist.push(_tempdeptid);
			if (_tempdeptid == "0")
			{
				return;
			}
			else
			{
				getFDept(_tempdeptid, deptlist);
			}
		}

		//历史寻呼
		private function getCallContentHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getCallContentHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getCallContentErrorHandler);
		}

		private function getCallContentErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getCallContentHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getCallContentErrorHandler);
		}

		//更新关注人员
		private function updateCareUserInfoHandler(e:Event):void
		{
			var userInfo:UserInfo=cnet.data as UserInfo;
			var params:Array=new Array();
			params.push({key: "UID", value: userInfo.UserID});
			params.push({key: "UserName", value: userInfo.UserName});
			params.push({key: "DeptName", value: userInfo.DeptName});
			params.push({key: "PosiName", value: userInfo.PosiName});
			params.push({key: "TeleNum", value: userInfo.TeleNum});
			params.push({key: "UserTel", value: userInfo.UserTel});
			params.push({key: "TUID", value: config.LoginCode});
			var sql:String="update UserCare set UserName=@UserName,DeptName=@DeptName,PosiName=@PosiName,TeleNum=@TeleNum,UserTel=@UserTel where TUID=@TUID and UID=@UID";
			var sqlHelper:SqlHelper=new SqlHelper();
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, params);

			this.data=userInfo;
			cnet.removeEventListener(Net.Event_Net_PostBack, updateCareUserInfoHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, updateCareUserInfoErrorHandler);
		}

		private function updateCareUserInfoErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, updateCareUserInfoHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, updateCareUserInfoErrorHandler);
		}

		//附件下载
		private function getFileHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getFileHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getFileErrorHandler);
		}

		private function getFileErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getFileHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getFileErrorHandler);
		}

		//日记保存
		private function saveDiaryHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, saveDiaryHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, saveDiaryErrorHandler);
		}

		private function saveDiaryErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, saveDiaryHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, saveDiaryErrorHandler);
		}

		//获取个人日记
		private function getDiaryListHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getDiaryListHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getDiaryListErrorHandler);
		}

		private function getDiaryListErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getDiaryListHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getDiaryListErrorHandler);
		}

		//设置寻呼已阅
		private function setMessageReadHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, setMessageReadHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, setMessageReadErrorHandler);
		}

		private function setMessageReadErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, setMessageReadHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, setMessageReadErrorHandler);
		}

		//寻呼回复
		private function replyUnreadMessageHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, replyUnreadMessageHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, replyUnreadMessageErrorHandler);
		}

		private function replyUnreadMessageErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, replyUnreadMessageHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, replyUnreadMessageErrorHandler);
		}

		//未阅寻呼
		private function getCallNoSeeHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getCallNoSeeHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getCallNoSeeErrorHandler);
		}

		private function getCallNoSeeErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getCallNoSeeHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getCallNoSeeErrorHandler);
		}

		//获取最新的未阅寻呼
		private function getLastCallNoSeeHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getLastCallNoSeeHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getLastCallNoSeeErrorHandler);
		}

		private function getLastCallNoSeeErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getLastCallNoSeeHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getLastCallNoSeeErrorHandler);
		}

		//获取未阅寻呼数量
		private function getUnreadMessageNumHandler(e:Event):void
		{
			this.data=cnet.data.Data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getUnreadMessageNumHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getUnreadMessageNumErrorHandler);
		}

		private function getUnreadMessageNumErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, getUnreadMessageNumHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getUnreadMessageNumErrorHandler);
		}

		//发送寻呼
		private function SendMsgHandler(e:Event):void
		{
			this.data="";
			cnet.removeEventListener(Net.Event_Net_PostBack, SendMsgHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, SendMsgErrorHandler);
		}

		private function SendMsgErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			cnet.removeEventListener(Net.Event_Net_PostBack, SendMsgHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, SendMsgErrorHandler);
		}

		//获取其他用户信息
		private function getOtherUserInfoHandler(e:Event):void
		{
			this.data=cnet.data;
			doAction(Event_App_Complate);
			cnet.removeEventListener(Net.Event_Net_PostBack, getOtherUserInfoHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getOtherUserInfoErrorHandler);
		}

		private function getOtherUserInfoErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			doAction(Event_App_Error);
			cnet.removeEventListener(Net.Event_Net_PostBack, getOtherUserInfoHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getOtherUserInfoErrorHandler);
		}

		//组织结构
		private function getUserListHandler(e:Event):void
		{
			var org:Org=new Org();
			org.ChildNodes=new Vector.<Dept>();
			org.ChildUsers=new Vector.<User>();
			var hnode:Dept=null;
			var data:Object=cnet.data;

			for (var i:int=0; i < data.DeptList.length; i++)
			{
				hnode=new Dept();
				hnode.DeptName=String(data.DeptList[i].DeptName);
				hnode.DeptID=String(data.DeptList[i].DeptId);
				hnode.DeptFID=String(data.DeptList[i].FatherId);
				hnode.Level=int(data.DeptList[i].Level);
				if (String(data.DeptList[i].DeptName).indexOf('******') < 0)
				{
					hnode.ChildUsers=new Vector.<User>();
					var user:User=null;
					var userList:Object=data.DeptList[i].ChildUsers;
					for (var p:int=0, lens:int=userList.length; p < lens; p++)
					{
						user=new User();
						user.Color=String(userList[p].Color).toLowerCase();
						user.DeptID=String(userList[p].DeptId);
						user.UserID=String(userList[p].UserId);
						user.PosiID=String(userList[p].PosiId);
						user.UserName=String(userList[p].UserName);
						hnode.ChildUsers.push(user);
					}
				}
				hnode.ChildNodes=new Vector.<Dept>();
				var dept:Dept=null;
				var deptList:Object=data.DeptList[i].ChildNodes;
				for (var j:int=0, len:int=deptList.length; j < len; j++)
				{
					dept=new Dept();
					dept.DeptFID=String(deptList[j].FatherId);
					dept.DeptID=String(deptList[j].DeptId);
					dept.DeptName=String(deptList[j].DeptName);
					hnode.ChildNodes.push(dept);
				}
				org.Error=false;
				org.ErrorMessage="";
				org.ChildNodes.push(hnode);
			}

			//缓存数据
			cacheUserList(data);
			updateCache((new Date()).valueOf().toString());
			this.data=org;
			//回调
			doAction(Event_App_Complate);
			cnet.removeEventListener(Net.Event_Net_PostBack, getUserListHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getUserListErrorHandler);
		}

		private function getUserListErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			doAction(Event_App_Error);
			cnet.removeEventListener(Net.Event_Net_PostBack, getUserListHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getUserListErrorHandler);
		}

		//缓存部门列表到本地数据库减少网络请求次数
		private function cacheDeptNodes(deptNode:Object, sqlHelper:SqlHelper):void
		{
			var sql:String="insert into dept(DeptID,DeptFID,DeptName,Level) values(@DeptID,@DeptFID,@DeptName,@Level)";
			var params:Array=new Array();
			params.push({key: "DeptID", value: deptNode.DeptId});
			params.push({key: "DeptFID", value: deptNode.FatherId});
			params.push({key: "DeptName", value: deptNode.DeptName});
			params.push({key: "Level", value: deptNode.Level});
			sqlHelper.execSqlofTrans(sql, params);

			for (var i:int=0; i < deptNode.ChildUsers.length; i++)
			{
				sql="insert into user(UserID,UserName,DeptID,PosiID,Color) values(@UserID,@UserName,@DeptID,@PosiID,@Color)";
				params.splice(0, params.length);
				params.push({key: "UserID", value: deptNode.ChildUsers[i].UserId});
				params.push({key: "UserName", value: deptNode.ChildUsers[i].UserName});
				params.push({key: "DeptID", value: deptNode.DeptId});
				params.push({key: "PosiID", value: deptNode.ChildUsers[i].PosiId});
				params.push({key: "Color", value: deptNode.ChildUsers[i].Color});
				sqlHelper.execSqlofTrans(sql, params);
			}
			if (deptNode.ChildNodes.length != 0)
			{
				for (var j:int=0; i < deptNode.ChildNodes.length; j++)
				{
					cacheDeptNodes(deptNode.ChildNodes[j], sqlHelper);
				}
			}
		}

		//提取登录者信息
		private function getUserInfoHandler(e:Event):void
		{
			this.data=cnet.data;
			doAction(Event_App_Complate);
			cnet.removeEventListener(Net.Event_Net_PostBack, getUserInfoHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getUserInfoErrorHandler);
		}

		private function getUserInfoErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			doAction(Event_App_Error);
			cnet.removeEventListener(Net.Event_Net_PostBack, getUserInfoHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, getUserInfoErrorHandler);
		}

		//用户登录
		private function loginHandler(e:Event):void
		{
			this.data="";
			setConfig(config);
			doAction(Event_App_Complate);
			cnet.removeEventListener(Net.Event_Net_PostBack, loginHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, loginErrorHandler);
		}

		private function loginErrorHandler(e:Event):void
		{
			this.data=cnet.data;
			doAction(Event_App_Error);
			cnet.removeEventListener(Net.Event_Net_PostBack, loginHandler);
			cnet.removeEventListener(Net.Event_Net_PostError, loginErrorHandler);
		}

		//处理自定义事件
		private function doAction(eventName:String):void
		{
			var event:Event=new Event(eventName);

			_eventDispatcher.dispatchEvent(event);
		}
		/**
		 * private function end
		 *****************************************************/

		/*****************************************************
		 * 事件注册函数开始
		 */

		/**
		 * 事件注册函数
		 */
		public function addEventListener(type:String, listener:Function):void
		{
			_eventDispatcher.addEventListener(type, listener);
		}

		/**
		 * 移除事件注册
		 */
		public function removeEventListener(type:String, listener:Function):void
		{
			_eventDispatcher.removeEventListener(type, listener);
		}

		/**
		 * 事件注册函数结束
		 *****************************************************/

		


		/****************************************************
		 * public function start
		 */

		/**
		 * 构造函数
		 */
		public function App()
		{
			_eventDispatcher=new EventDispatcher();
			cnet=new Net();
			data=new Object();
			config=getConfig();
		}

		/**
		 * 同步
		 * 获取程序配置信息
		 */
		public function getConfig():Config
		{
			var sqlHelper:SqlHelper=new SqlHelper();
			var config:Config=new Config();
			var sql:String="select * from config";
			var sqlData:SqlData=sqlHelper.execSql(sql);
			config.Error=false;
			if (sqlData.Error)
			{
				config.Error=true;
				config.ErrorMessage=sqlData.ErrorMessage;
				return config;
			}
			if (sqlData.DataTable == null)
			{
				config.Error=true;
				config.ErrorMessage=LnConst.DbEmptyError;
				return config;
			}
			else
			{
				for (var i:int=0; i < sqlData.DataTable.length; i++)
				{
					config[String(sqlData.DataTable[i].Key)]=String(sqlData.DataTable[i].Value);
				}
			}
			return config;
		}

		/**
		 * 同步
		 * 检测系统是否需要更新数据
		 */
		public function checkUpdate():Boolean
		{
			//检查是否需要更新
			var isupdate:Boolean=false;
			//读取数据库缓存信息
			var cacheInfo:CacheInfo=getCacheInfo();
			if (cacheInfo.Error)
				return true;
			var slice:uint=0;
			if (cacheInfo.Error)
				slice=0
			else
				slice=Math.round((new Date()).valueOf()) - Math.round(cacheInfo.Org);
			if (slice == 0 || slice > AppConst.CacheTimeout)
			{
				isupdate=true;
			}
			return isupdate;
		}

		/**
		 * 同步
		 * 设置系统配置信息
		 */
		public function setConfig(config:Config):ReturnMsg
		{
			var params:Array=new Array();
			var data:Array=new Array();
			params.push("value");
			params.push("key");
			for each (var cname:String in config)
			{
				data.push({"value": config[cname], "key": cname});
			}
			var sqlHelper:SqlHelper=new SqlHelper();
			var sql:String="insert or replace into config (Key,Value) values(@key,@value)";
			var sqlData:SqlData=sqlHelper.execTrans(sql, params, data);
			var returnMsg:ReturnMsg=new ReturnMsg();
			returnMsg.Error=sqlData.Error;
			returnMsg.ErrorMessage=sqlData.ErrorMessage;
			return returnMsg;
		}

		/**
		 * 同步
		 * 更新缓存时间
		 */
		public function updateCache(time:String):ReturnMsg
		{
			var sqlHelper:SqlHelper=new SqlHelper();
			var params:Array=new Array();
			params.push({key: "org", value: time});
			var sql:String="insert or replace into config (Org) values(@org)";
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, params);
			var returnMsg:ReturnMsg=new ReturnMsg();
			returnMsg.Error=sqlData.Error;
			returnMsg.ErrorMessage=sqlData.ErrorMessage;
			return returnMsg;
		}

		/**
		 * 异步
		 * 登录
		 */
		public function login(loginCode:String, pwd:String, rembPwd:Boolean, autoLogin:Boolean):void
		{
			config=this.getConfig();
			//直接触发错误事件
			if (config.Error)
			{
				this.data=config.ErrorMessage;
				doAction(Event_App_Error);
				return;
			}
			//web service 登录认证地址
			var url:String=config.WsURL + "/Authorize";
			var rdata:Object=new Object();
			rdata.sign=loginCode + "$" + Encryption.encrypt(pwd, "SHA1");
			cnet.addEventListener(Net.Event_Net_PostBack, loginHandler);
			cnet.addEventListener(Net.Event_Net_PostError, loginErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
			if (config.LoginCode !== loginCode)
			{
				config.CallNum=0;
			}
			config.LoginCode=loginCode;
			config.Password=pwd;
			config.RembPwd=rembPwd;
			config.AutoLogin=autoLogin;
		}

		/**
		 * 异步
		 * 获取登录账号信息
		 */
		public function getUserInfo(loginCode:String):void
		{
			if (config.Error)
			{
				this.data=config.ErrorMessage;
				doAction(Event_App_Error);
				return;
			}
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetUserInfo";
			var rdata:Object=new Object();
			rdata.sign=loginCode + "$" + Encryption.encrypt(config.Password, "SHA1");

			cnet.addEventListener(Net.Event_Net_PostBack, getUserInfoHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getUserInfoErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 同步
		 * 缓存组织架构信息
		 */
		public function cacheUserList(data:Object):ReturnMsg
		{
			var returnMsg:ReturnMsg=new ReturnMsg();
			//创建数据库操作对象		
			var sqlHelper:SqlHelper=new SqlHelper();
			//删除部门和用户信息
			if (sqlHelper.execSql("delete from dept").Error || sqlHelper.execSql("delete from user").Error)
			{
				returnMsg.Error=true;
				returnMsg.ErrorMessage=LnConst.DbError;
				return returnMsg;
			}

			//开始一个数据库事务
			sqlHelper.BegionTrans();
			var sql:String="";
			for (var i:int=0; i < data.DeptList.length; i++)
			{
				sql="insert into dept(DeptID,DeptFID,DeptName,Level) values(@DeptID,@DeptFID,@DeptName,@Level)";
				var params:Array=new Array();
				params.push({key: "DeptID", value: data.DeptList[i].DeptId});
				params.push({key: "DeptFID", value: data.DeptList[i].FatherId});
				params.push({key: "DeptName", value: data.DeptList[i].DeptName});
				params.push({key: "Level", value: data.DeptList[i].Level});
				sqlHelper.execSqlofTrans(sql, params);
				for (var k:int=0; k < data.DeptList[i].ChildUsers.length; k++)
				{
					sql="insert into user(UserID,UserName,DeptID,PosiID,Color) values(@UserID,@UserName,@DeptID,@PosiID,@Color)";
					params.splice(0, params.length);
					params.push({key: "UserID", value: data.DeptList[i].ChildUsers[k].UserId});
					params.push({key: "UserName", value: data.DeptList[i].ChildUsers[k].UserName});
					params.push({key: "DeptID", value: data.DeptList[i].DeptId});
					params.push({key: "PosiID", value: data.DeptList[i].ChildUsers[k].PosiId});
					params.push({key: "Color", value: data.DeptList[i].ChildUsers[k].Color});
					sqlHelper.execSqlofTrans(sql, params);
				}
				for (var j:int=0; j < data.DeptList[i].ChildNodes.length; j++)
				{
					cacheDeptNodes(data.DeptList[i].ChildNodes[j], sqlHelper);
				}
			}
			//提交事务
			var sqlData:SqlData=sqlHelper.CommitTrans();
			returnMsg.Error=sqlData.Error;
			returnMsg.ErrorMessage=sqlData.ErrorMessage;
			return returnMsg;
		}

		/**
		 * 同步
		 * 检测某用户是否在关注列表
		 */
		public function checkCare(uid:String):Boolean
		{
			if (config.Error)
				return false;
			var sqlHelper:SqlHelper=new SqlHelper();
			var params:Array=new Array();
			params.push({key: "UID", value: uid});
			params.push({key: "TUID", value: config.LoginCode});
			var sql:String="select count(*) Num from UserCare where UID = @UID and TUID = @TUID";
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, params);
			if (sqlData.Error)
				return false;
			if (Number(sqlData.DataTable[0].Num) == 0)
				return false;
			else
				return true;
		}

		/**
		 * 同步
		 * 加载一级部门和用户
		 */
		public function getUserListFromCache():Org
		{
			//返回数据
			var org:Org=new Org();
			org.ChildNodes=new Vector.<Dept>();
			org.ChildUsers=new Vector.<User>();
			var sqlHelper:SqlHelper=new SqlHelper();
			var sql:String="select * from dept where deptfid = 0";
			var sqlData:SqlData=sqlHelper.execSql(sql);
			if (sqlData.Error)
			{
				org.Error=sqlData.Error;
				org.ErrorMessage=sqlData.ErrorMessage;
				return org;
			}
			if (sqlData.DataTable == null)
			{
				org.Error=sqlData.Error;
				org.ErrorMessage=LnConst.DbEmptyError;
				return org;
			}
			else
			{
				var hnode:Dept=null;
				for (var i:int=0; i < sqlData.DataTable.length; i++)
				{
					hnode=new Dept();
					hnode.DeptName=String(sqlData.DataTable[i].DeptName);
					hnode.DeptID=String(sqlData.DataTable[i].DeptID);
					hnode.Level=int(sqlData.DataTable[i].Level);
					if (hnode.DeptName.indexOf('******') < 0)
					{
						sql="select * from user where deptid= '" + sqlData.DataTable[i].DeptID + "'";
						var userData:SqlData=sqlHelper.execSql(sql);
						if (userData.Error)
						{
							org.Error=true;
							org.ErrorMessage=userData.ErrorMessage;
							return org;
						}
						if (userData.DataTable != null)
						{
							hnode.ChildUsers=new Vector.<User>();
							var user:User=null;
							for (var k:int=0; k < userData.DataTable.length; k++)
							{
								user=new User();
								user.Color=String(userData.DataTable[k].Color);
								user.UserID=String(userData.DataTable[k].UserID);
								user.DeptID=String(userData.DataTable[k].DeptID);
								user.PosiID=String(userData.DataTable[k].PosiID);
								user.UserName=String(userData.DataTable[k].UserName);
								hnode.ChildUsers.push(user);
							}
						}
					}

					sql="select * from dept where deptfid = '" + sqlData.DataTable[i].DeptID + "'";
					var deptData:SqlData=sqlHelper.execSql(sql);
					if (deptData.Error)
					{
						org.Error=deptData.Error;
						org.ErrorMessage=deptData.ErrorMessage;
						return org;
					}
					if (deptData.DataTable != null)
					{
						var dept:Dept=null;
						for (var j:int=0; j < deptData.DataTable.length; j++)
						{
							dept=new Dept();
							dept.DeptID=String(deptData.DataTable[j].DeptID);
							dept.DeptFID=String(deptData.DataTable[j].DeptFID);
							dept.DeptName=String(deptData.DataTable[j].DeptName);
							dept.Level=int(deptData.DataTable[j].Level);
						}
					}
					org.ChildNodes.push(hnode);
				}
			}
			return org;
		}

		/**
		 * 同步
		 * 加载子部门和用户
		 */
		public function getChildUserList(deptId:String):Org
		{
			//返回数据
			var org:Org=new Org();
			org.ChildNodes=new Vector.<Dept>();
			org.ChildUsers=new Vector.<User>();
			//创建数据库操作对象		
			var sqlHelper:SqlHelper=new SqlHelper();
			var sql:String="select * from user where deptid= @deptid";
			var params:Array=new Array();
			params.push({key: "deptid", value: deptId});
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, params);
			if (sqlData.Error)
			{
				org.Error=sqlData.Error;
				org.ErrorMessage=sqlData.ErrorMessage;
				return org;
			}
			if (sqlData.DataTable != null)
			{
				var user:User=null;
				for (var k:int=0; k < sqlData.DataTable.length; k++)
				{
					user=new User();
					user.Color=String(sqlData.DataTable[k].Color);
					user.UserID=String(sqlData.DataTable[k].UserID);
					user.UserName=String(sqlData.DataTable[k].UserName);
					user.DeptID=String(sqlData.DataTable[k].DeptID);
					user.PosiID=String(sqlData.DataTable[k].PosiID);
					org.ChildUsers.push(user);
				}
			}
			sql="select * from dept where deptfid = @deptid";
			params.length=0;
			params.push({key: "deptid", value: deptId});
			sqlData=sqlHelper.execSqlWithParams(sql, params);
			if (sqlData.Error)
			{
				org.Error=sqlData.Error;
				org.ErrorMessage=sqlData.ErrorMessage;
				return org;
			}
			if (sqlData.DataTable != null)
			{
				var dept:Dept=null;
				for (var j:int=0; j < sqlData.DataTable.length; j++)
				{
					dept=new Dept();
					dept.DeptID=String(sqlData.DataTable[j].DeptID);
					dept.DeptFID=String(sqlData.DataTable[j].DeptFID);
					dept.DeptName=String(sqlData.DataTable[j].DeptName);
					dept.Level=int(sqlData.DataTable[j].Level);
					org.ChildNodes.push(dept);
				}
			}
			return org;
		}

		/**
		 * 异步
		 * 首次加载组织架构，网络请求数据
		 */
		public function getUserList():void
		{
			//默认用户已经登录成功		
			if (config.Error)
			{
				this.data=config.ErrorMessage;
				doAction(Event_App_Error);
				return;
			}
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetUserList";
			var rdata:Object=new Object();
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.dataStyle="0";
			cnet.addEventListener(Net.Event_Net_PostBack, getUserListHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getUserListErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 同步
		 * 获取数据缓存时间的配置信息
		 */
		public function getCacheInfo():CacheInfo
		{
			var sqlHelper:SqlHelper=new SqlHelper();
			var sqlData:SqlData=sqlHelper.execSql("select * from cache");
			var cacheInfo:CacheInfo=new CacheInfo();
			if (sqlData.Error)
			{
				cacheInfo.Error=true;
				cacheInfo.ErrorMessage=sqlData.ErrorMessage;
				return cacheInfo;
			}
			if (sqlData.DataTable == null)
			{
				cacheInfo.Error=true;
				cacheInfo.ErrorMessage=LnConst.DbEmptyError;
				return cacheInfo;
			}
			cacheInfo.Org=uint(Number(sqlData.DataTable[0].Org));
			cacheInfo.Error=false;
			cacheInfo.ErrorMessage="";
			return cacheInfo;
		}

		/**
		 * 异步
		 * 获取其他用户信息
		 */
		public function getOtherUserInfo(userId:String):void
		{
			//默认用户已经登录成功			
			if (config.Error)
			{
				this.data=config.ErrorMessage;
				doAction(Event_App_Error);
				return;
			}
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetOUserInfo";
			var rdata:Object=new Object();
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.userId=userId;
			cnet.addEventListener(Net.Event_Net_PostBack, getOtherUserInfoHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getOtherUserInfoErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}


		/**
		 * 异步
		 * 寻呼发送
		 */
		public function SendMsg(msg:Msg):void
		{
			//默认用户已经登录成功		
			if (config.Error)
			{
				this.data=config.ErrorMessage;
				doAction(Event_App_Error);
				return;
			}
			//web service 登录认证地址
			var url:String=config.WsURL + "/SendCall";
			var rdata:Object=new Object();
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");

			//寻呼内容
			rdata.strSendContent=msg.SendContent;
			//目标人
			rdata.strSendToUsers=msg.SendToUsers;
			//是否发短信
			rdata.strSmsSign=msg.SmsSign;
			//手机号
			rdata.strMobileNum=msg.MobileNum;

			cnet.addEventListener(Net.Event_Net_PostBack, SendMsgHandler);
			cnet.addEventListener(Net.Event_Net_PostError, SendMsgErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 同步
		 * 添加人员到关注列表
		 */
		public function careUser(userinfo:UserInfo):ReturnMsg
		{
			var params:Array=new Array();
			params.push({key: "UID", value: userinfo.UserID});
			params.push({key: "UserName", value: userinfo.UserName});
			params.push({key: "DeptName", value: userinfo.DeptName});
			params.push({key: "PosiName", value: userinfo.PosiName});
			params.push({key: "TeleNum", value: userinfo.TeleNum});
			params.push({key: "UserTel", value: userinfo.UserTel});
			params.push({key: "TUID", value: config.LoginCode});
			var sqlHelper:SqlHelper=new SqlHelper();
			var sql:String="Insert or Replace into UserCare(TUID,UID,UserName,DeptName,PosiName,TeleNum,UserTel) values(@TUID,@UID,@UserName,@DeptName,@PosiName,@TeleNum,@UserTel)";
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, params);
			var returnMsg:ReturnMsg=new ReturnMsg();
			returnMsg.Error=sqlData.Error;
			returnMsg.ErrorMessage=sqlData.ErrorMessage;
			return returnMsg;
		}

		/**
		 * 同步
		 * 加载关注人员
		 */
		public function getCareUserList():CareUser
		{
			var careUser:CareUser=new CareUser();
			var params:Array=new Array();
			params.push({TUID: config.LoginCode});
			var sql:String="select * from UserCare where TUID=@TUID";
			var sqlHelper:SqlHelper=new SqlHelper();
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, params);
			if (sqlData.Error)
			{
				careUser.Error=sqlData.Error;
				careUser.ErrorMessage=sqlData.ErrorMessage;
				return careUser;
			}
			if (sqlData.DataTable == null)
			{
				careUser.Error=true;
				careUser.ErrorMessage=LnConst.DbEmptyError;
				return careUser;
			}
			var userList:Vector.<UserInfo>=new Vector.<UserInfo>();
			var userInfo:UserInfo=null;
			for (var i:int=0, len:int=sqlData.DataTable.length; i < len; i++)
			{
				userInfo=new UserInfo();
				userInfo.UserID=sqlData.DataTable[i].UserID;
				userInfo.UserName=sqlData.DataTable[i].UserName;
				userInfo.DeptName=sqlData.DataTable[i].DeptName;
				userInfo.PosiName=sqlData.DataTable[i].PosiName;
				userInfo.TeleNum=sqlData.DataTable[i].TeleNum;
				userInfo.UserTel=sqlData.DataTable[i].UserTel;
				userList.push(userInfo);
			}
			careUser.CareUserList=userList;
			return careUser;
		}

		/**
		 * 同步
		 * 清空关注人员
		 */
		public function clearCareUsers():ReturnMsg
		{
			var sqlHelper:SqlHelper=new SqlHelper();
			var sql:String="delete from UserCare";
			var sqlData:SqlData=sqlHelper.execSql(sql);
			var returnMsg:ReturnMsg=new ReturnMsg();
			returnMsg.Error=sqlData.Error;
			returnMsg.ErrorMessage=sqlData.ErrorMessage;
			return returnMsg;
		}

		/**
		 * 异步
		 * 请求未阅寻呼数量
		 */
		public function getUnreadMessageNum():void
		{
			//默认用户已经登录成功		
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetUnreadMessageNum";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			cnet.addEventListener(Net.Event_Net_PostBack, getUnreadMessageNumHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getUnreadMessageNumErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 异步
		 * 提取最新未阅寻呼
		 */
		public function getLastCallNoSee():void
		{
			//默认用户已经登录成功			
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetUnreadMessageList";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.cursor="1";
			rdata.count="1";
			cnet.addEventListener(Net.Event_Net_PostBack, getLastCallNoSeeHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getLastCallNoSeeErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 异步
		 * 未阅寻呼
		 */
		public function getCallNoSee(cursor:String, count:String):void
		{
			//默认用户已经登录成功
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetUnreadMessageList";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.cursor=cursor;
			rdata.count=count;
			cnet.addEventListener(Net.Event_Net_PostBack, getCallNoSeeHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getCallNoSeeErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 异步
		 * 寻呼回复
		 */
		public function replyUnreadMessage(replyId:String, content:String):void
		{
			//默认用户已经登录成功			
			//web service 登录认证地址
			var url:String=config.WsURL + "/ReplyUnreadMessage";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.replyId=replyId;
			rdata.content=content;
			cnet.addEventListener(Net.Event_Net_PostBack, replyUnreadMessageHandler);
			cnet.addEventListener(Net.Event_Net_PostError, replyUnreadMessageErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 异步
		 * 寻呼设置已阅
		 */
		public function setMessageRead(id:String):void
		{
			//默认用户已经登录成功			
			//web service 登录认证地址
			var url:String=config.WsURL + "/SetMessageRead";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.messageIds=id;
			cnet.addEventListener(Net.Event_Net_PostBack, setMessageReadHandler);
			cnet.addEventListener(Net.Event_Net_PostError, setMessageReadErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 异步
		 * 获取个人日记列表
		 */
		public function getDiaryList(cursor:String, count:String):void
		{
			//默认用户已经登录成功			
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetDiaryList";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.cursor=cursor;
			rdata.count=count;
			cnet.addEventListener(Net.Event_Net_PostBack, getDiaryListHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getDiaryListErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 异步
		 * 日记保存
		 */
		public function saveDiary(content:String):void
		{
			//默认用户已经登录成功			
			//web service 登录认证地址
			var url:String=config.WsURL + "/SaveDiary";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.diaryContent=content;
			cnet.addEventListener(Net.Event_Net_PostBack, saveDiaryHandler);
			cnet.addEventListener(Net.Event_Net_PostError, saveDiaryErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}


		/**
		 * 异步
		 * 文件下载
		 */
		public function getFile(fileId:String, part:String):void
		{
			//默认用户已经登录成功			
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetFile";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.fileId=fileId;
			rdata.part=part;
			cnet.addEventListener(Net.Event_Net_PostBack, getFileHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getFileErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}


		/**
		 * 同步
		 * 人员搜索
		 */
		public function getSearchData(tip:String):ReturnMsg
		{
			var params:Array=new Array();
			params.push({key: "tip", value: "%" + tip + "%"});
			var sql:String="select * from user  where username like @tip";
			var sqlHelper:SqlHelper=new SqlHelper();
			var sqlData:SqlData=sqlHelper.execSqlWithParams(sql, params);
			var returnMsg:ReturnMsg=new ReturnMsg();
			if (sqlData.Error)
			{
				returnMsg.Error=sqlData.Error;
				returnMsg.ErrorMessage=sqlData.ErrorMessage;
				return returnMsg;
			}
			if (sqlData.DataTable == null)
			{
				returnMsg.Error=true;
				returnMsg.ErrorMessage=LnConst.DbEmptyError;
				return returnMsg;
			}
			var _tempdeptid:String="";
			if (sqlData.DataTable.length > 0)
				_tempdeptid=String(sqlData.DataTable[0]["DeptID"]);
			else
				_tempdeptid="0";

			if (_tempdeptid == "0")
			{
				returnMsg.Error=false;
				returnMsg.ErrorMessage="";
				return returnMsg;
			}
			var deptList:Array=new Array();
			deptList[0]=_tempdeptid;
			getFDept(_tempdeptid, deptList);
			returnMsg.Error=false;
			returnMsg.ErrorMessage=deptList.join(",");
			return returnMsg;
		}

		/**
		 * 异步
		 * 更新关注人员
		 */
		public function updateCareUserInfo(uid:String):void
		{
			//默认用户已经登录成功		
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetOUserInfo";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			//指定用户ID
			rdata.userId=uid;
			cnet.addEventListener(Net.Event_Net_PostBack, updateCareUserInfoHandler);
			cnet.addEventListener(Net.Event_Net_PostError, updateCareUserInfoErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 异步
		 * 历史寻呼
		 */
		public function getCallContent(callId:String):void
		{
			//默认用户已经登录成功			
			//web service 登录认证地址
			var url:String=config.WsURL + "/GetCallContent";
			var rdata:Object=new Object();
			//用户名和密码用$连接
			rdata.sign=config.LoginCode + "$" + Encryption.encrypt(config.Password, "SHA1");
			rdata.callId=callId;
			cnet.addEventListener(Net.Event_Net_PostBack, getCallContentHandler);
			cnet.addEventListener(Net.Event_Net_PostError, getCallContentErrorHandler);
			cnet.getJSON(url, JSON.encode(rdata));
		}

		/**
		 * 同步
		 * 升级新版本前备份配置文件以及关注人员
		 */
		public function backupToXML():ReturnMsg
		{
			var returnMsg:ReturnMsg=new ReturnMsg();
			var xmlStr:String="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
			xmlStr+="<careusers>";
			var careUsers:CareUser=getCareUserList();
			if (careUsers.Error)
			{
				returnMsg.Error=true;
				returnMsg.ErrorMessage=careUsers.ErrorMessage;
				return returnMsg;
			}
			for (var i:int=0, len:int=careUsers.CareUserList.length; i < len; i++)
			{
				xmlStr+="<item>";
				xmlStr+="<UID>" + careUsers.CareUserList[i].UserID + "</UID>";
				xmlStr+="<UserName>" + careUsers.CareUserList[i].UserName + "</UserName>";
				xmlStr+="<DeptName>" + careUsers.CareUserList[i].DeptName + "</DeptName>";
				xmlStr+="<PosiName>" + careUsers.CareUserList[i].PosiName + "</PosiName>";
				xmlStr+="<TeleNum>" + careUsers.CareUserList[i].TeleNum + "</TeleNum>";
				xmlStr+="<UserTel>" + careUsers.CareUserList[i].UserTel + "</UserTel>";
				xmlStr+="<TUID>" + config.LoginCode + "</TUID>";
				xmlStr+="</item>";
			}
			xmlStr+="</careusers>";
			xmlStr+="<config>";
			for each (var cname:String in config)
			{
				if (config[cname] == "")
				{

					xmlStr+="<item key=\"" + cname + "\">";
					xmlStr+=config[cname].toString();
					xmlStr+="</item>";
				}
			}
			xmlStr+="</config>";
			var file:File=new File(File.applicationDirectory.resolvePath(AppConst.BakPath).nativePath);
			var stream:FileStream=new FileStream();
			stream.open(file, FileMode.WRITE);
			stream.writeUTFBytes(xmlStr);
			stream.close();
			returnMsg.Error=false;
			returnMsg.ErrorMessage=xmlStr;
			return returnMsg;
		}

		/**
		 * 同步
		 * 从XML配置文件恢复配置信息
		 */
		public function recoverFromXML():ReturnMsg
		{

			var returnMsg:ReturnMsg=new ReturnMsg();
			var file:File=new File(File.applicationDirectory.resolvePath(AppConst.BakPath).nativePath);
			if (file.exists)
			{
				var stream:FileStream=new FileStream();
				stream.open(file, FileMode.READ);
				var xmlDom:XML=XML(stream.readUTFBytes(stream.bytesAvailable));
				var sqlHelper:SqlHelper=new SqlHelper();
				sqlHelper.BegionTrans();

				//恢复关注人员			
				var sql:String="insert or replace into Usercare(UID,UserName,DeptName,PosiName,TeleNum,UserTel,TUID) values(@UID,@UserName,@DeptName,@PosiName,@TeleNum,@UserTel,@TUID)";
				var params:Array=new Array();
				var item:XML=null;
				for each (item in xmlDom.careusers.item)
				{
					params.splice(0, params.length);
					params.push({key: "UID", value: item.UID});
					params.push({key: "UserName", value: item.UserName});
					params.push({key: "DeptName", value: item.DeptName});
					params.push({key: "PosiName", value: item.PosiName});
					params.push({key: "TeleNum", value: item.TeleNum});
					params.push({key: "UserTel", value: item.UserTel});
					params.push({key: "TUID", value: item.TUID});
					sqlHelper.execSqlofTrans(sql, params);
				}
				//恢复配置信息
				sql="update config set Value=@Value where Key=@Key";
				for each (item in xmlDom.config.item)
				{
					params.splice(0, params.length);
					params.push({key: "Key", value: item.attribute("key")});
					params.push({key: "Value", value: item.text().toString()});
					sqlHelper.execSqlofTrans(sql, params);
				}
				//恢复完成，删除备份文件
				file.deleteFile();
				var sqlData:SqlData=sqlHelper.CommitTrans();
				if (sqlData.Error)
				{
					returnMsg.Error=sqlData.Error;
					returnMsg.ErrorMessage=sqlData.ErrorMessage;
					return returnMsg;
				}
			}
			return returnMsg;
		}
		
		/**
		 * public function end
		 *************************************************************/
	}
}
